import { defineStore } from 'pinia'
import pinia from '@/stores'
import { reqUserSessionList } from "@/api/user/message";
import { useUserStore } from "./user";
import SockJS from "sockjs-client/dist/sockjs.min.js";
import Stomp from "stompjs";
import noticeSound from '@/assets/notice.mp3'; // 直接导入音频文件

const userStore = useUserStore(pinia);

export const useMessageStore = defineStore('messageStore', {
    state: () => {
        return {
            socketEndpoint: '/api/user/ws/',
            connectMap: new Map(),
            chatList: [],
            // 音频相关状态
            audioContext: null as (AudioContext | null),
            audioBuffer: null as (AudioBuffer | null),
            sourceNode: null as (AudioBufferSourceNode | null),
            notificationSound: noticeSound,
            sessionList: []
        }
    },
    actions: {
        // 初始化音频上下文
        initAudioContext() {
            if (!this.audioContext) {
                this.audioContext = new (window.AudioContext || (window as any).webkitAudioContext)();
            }
        },

        // 加载音频文件
        async loadAudio() {
            try {
                if (!this.audioContext) this.initAudioContext();

                const response = await fetch(this.notificationSound);
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                const arrayBuffer = await response.arrayBuffer();
                this.audioBuffer = await this.audioContext!.decodeAudioData(arrayBuffer);
            } catch (error) {
                console.error('加载音频失败:', error);
            }
        },

        // 播放通知音效
        async playNotificationSound() {
            try {
                if (!this.audioContext) this.initAudioContext();

                if (!this.audioBuffer) {
                    await this.loadAudio();
                    if (!this.audioBuffer) {
                        console.error('音频缓冲区为空');
                        return;
                    }
                }

                // 停止当前正在播放的声音
                if (this.sourceNode) {
                    this.sourceNode.stop();
                }

                // 创建并播放声音
                this.sourceNode = this.audioContext!.createBufferSource();
                this.sourceNode.buffer = this.audioBuffer;
                this.sourceNode.connect(this.audioContext!.destination);
                this.sourceNode.start(0);
            } catch (error) {
                console.error('播放通知音效出错:', error);
            }
        },

        // 创建连接池
        createConnect() {
            if (userStore.token) {
                this.subscribe()
                reqUserSessionList().then((res) => {
                    if (res.code === 200) {
                        this.sessionList = res.data;
                        this.sessionList.forEach((item) => {
                            const sessionId = item.sessionId;

                            // 每个会话都创建新的 SockJS 连接
                            const socket = new SockJS(this.socketEndpoint);
                            const stompClient = Stomp.over(socket);

                            stompClient.connect(
                                { token: userStore.token },
                                () => {
                                    console.log("连接成功 sessionId:" + sessionId);
                                    stompClient.subscribe("/user/message/" + sessionId, (res) => {
                                        console.log('收到消息', res.body);
                                        const entity = JSON.parse(res.body);

                                        if (entity.userId !== userStore.userId) {
                                            entity.role = 'assistant';
                                            this.currentMessage = entity;
                                            this.playNotificationSound();
                                        } else {
                                            entity.name = '自己';
                                        }
                                        this.chatList.push(entity);
                                    });
                                },
                                (error) => {
                                    console.log("连接失败: " + sessionId);
                                }
                            );
                        });
                    }
                });
            }
        },
        subscribe() {
            const socket = new SockJS(this.socketEndpoint);
            const stompClient = Stomp.over(socket);

            stompClient.connect(
                { token: userStore.token },
                () => {
                    console.log("订阅在线离线推送成功！",userStore.userId);
                    stompClient.subscribe("/user/online/" + userStore.userId, (res) => {
                        const body = JSON.parse(res.body);
                        this.playNotificationSound();
                        let sign = false
                        if (body.type == 1) {
                            body.content = '上线了'
                            sign = true;
                        } else {
                            body.content = '下线了'
                        }
                        this.sessionList.forEach((item) => {
                            if (item.userId == body.userId) {
                                item.online = sign;
                            }
                        })
                        this.currentMessage = body;
                    });
                },
                (error) => {
                    console.log("订阅在线离线推送失败");
                }
            );
        },
        // 连接池添加连接
        addConnect() {
            // 你的实现代码
        },
    },
    getters: {},
});
